package com.itboye.ihomebank.activity.key;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.itboye.ihomebank.KeyFragment;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.adapter.key.ItemICCardAdapter;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.ICCardListBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.custom.MyListView;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.ttKey.BleConstant;
import com.itboye.ihomebank.ttKey.Operation;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.UIAlertView;
import com.ttlock.bl.sdk.scanner.ExtendedBluetoothDevice;
import com.umeng.message.common.Const;
import com.itboye.ihomebank.ttKey.Key;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

import static com.itboye.ihomebank.KeyFragment.keysChangAn;
import static com.itboye.ihomebank.KeyFragment.mTTLockAPI;
import static com.itboye.ihomebank.util.SPUtils.get;

/**
 * Created by Administrator on 2018/8/7 0007.
 */

public class ActivityICCardList extends BaseOtherActivity implements Observer{
    View v_statusbar;
    ImageView close_icon,img_other;
    TextView add_shap_title_tv;

    LinearLayout liner_nokey;//无数据时
    MyListView xlistview;
    PtrClassicFrameLayout commend_anchor_ptr;
    public static Key localKey;
    LinearLayout selectICCard;
    TextView clearICCard,addICCard;
    private ExtendedBluetoothDevice device;
    boolean isShow;
    String uid;
    UserPresenter userPresenter;
    List<ICCardListBean.ICCardBean> mList;
    ItemICCardAdapter mAdapter;
    private UIAlertView uiAlertView;//删除IC卡

    public static String cardId;
    public static String cardNo;
    @Override
    protected int layout_id() {
        return R.layout.activity_iccard_list;
    }

    @Override
    protected void onInitController() {

    }

    @Override
    protected void onInit() {
        setStatusBarHeight(v_statusbar);
        img_other.setVisibility(View.VISIBLE);
        img_other.setImageDrawable(getResources().getDrawable(R.drawable.dianright));
        add_shap_title_tv.setText("IC卡");

        //请求打开蓝牙
        if (ActivityGuanLiKey.activity.equals("one")){
            KeyFragment.mTTLockAPI.requestBleEnable(this);
        }else {
            ActivityGuanLiKey.mTTLockAPI.requestBleEnable(this);
        }


        mList=new ArrayList<>();
        mAdapter=new ItemICCardAdapter(this,mList);
        xlistview.setAdapter(mAdapter);

        isShow=true;
        uid = get(this, null, SPContants.USER_ID, "") + "";
        localKey= ActivityGuanLiKey.localKey;
//        Log.d("====activitylist",ActivityGuanLiKey.localKey.toString());
        userPresenter=new UserPresenter(this);

        commend_anchor_ptr.setLastUpdateTimeRelateObject(this);
        commend_anchor_ptr.postDelayed(new Runnable() {
            @Override
            public void run() {
                //ic卡列表请求接口
                userPresenter.icCardList(uid,localKey.getLockId(),"1","20","0");
                commend_anchor_ptr.autoRefresh();//自动刷新
            }
        }, 100);
        commend_anchor_ptr.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {//加载更多的时候
                //ic卡列表
                userPresenter.icCardList(uid,localKey.getLockId(),"1","20","0");

            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {//刷新开始
                userPresenter.icCardList(uid,localKey.getLockId(),"1","20","0");
            }
        });
        this.registerReceiver(mReceiver,getIntentFilter());

        xlistview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                uiAlertView = new UIAlertView(ActivityICCardList.this, "删除IC卡",
                        "是否删除该IC卡?", "是", "取消");
                uiAlertView.show();
                uiAlertView.setClicklistener(new UIAlertView.ClickListenerInterface() {
                    @Override
                    public void doLeft() {
                        //删除IC卡
                        cardId=mList.get(position).getCardid();
                        cardNo=mList.get(position).getCardnumber();
                        if (ActivityGuanLiKey.activity.equals("one")){
                            KeyFragment.bleSession.setOperation(Operation.DELETEICCARD);
                            KeyFragment.mTTLockAPI.connect(localKey.getLockMac());
                        }else {//纯门锁
                            ActivityGuanLiKey.bleSession.setOperation(Operation.DELETEICCARD);
                            ActivityGuanLiKey.mTTLockAPI.connect(localKey.getLockMac());
                        }
                        uiAlertView.dismiss();
                        showProgressDialog("正在删除ic卡请稍后...",true);
                    }

                    @Override
                    public void doRight() {
                        uiAlertView.dismiss();
                    }
                });

                return true;
            }
        });
    }


    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action.equals(BleConstant.ACTION_BLE_DEVICE)) {
                Bundle bundle = intent.getExtras();
                device = bundle.getParcelable(BleConstant.DEVICE);

//                foundDeviceAdapter.updateDevice(device);
            }
            else if(action.equals(BleConstant.DELETE_ICCARD)) {
                closeProgressDialog();
                ByAlert.alert("ic卡删除成功");
                userPresenter.icCardList(uid,localKey.getLockId(),"1","20","0");
            }
            else if(action.equals(BleConstant.CLEAR_ICCARD)) {
                closeProgressDialog();
                ByAlert.alert("ic卡列表清除成功");
                userPresenter.icCardList(uid,localKey.getLockId(),"1","20","0");
            }
        }
    };

    private IntentFilter getIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleConstant.ACTION_BLE_DEVICE);
        intentFilter.addAction(BleConstant.ACTION_BLE_DISCONNECTED);
        intentFilter.addAction(BleConstant.CLEAR_ICCARD);
        intentFilter.addAction(BleConstant.DELETE_ICCARD);
        return intentFilter;
    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){

            case R.id.close_icon://返回
                this.finish();
                break;
            case R.id.img_other:
                if (isShow){
                    selectICCard.setVisibility(View.VISIBLE);
                }else {
                    selectICCard.setVisibility(View.GONE);
                }
                isShow=!isShow;
                break;

            case R.id.clearICCard:
                selectICCard.setVisibility(View.GONE);
                isShow=!isShow;
                if (mList.size()>0){
                    if (ActivityGuanLiKey.activity.equals("one")){
                        KeyFragment.bleSession.setOperation(Operation.CLEARICCARD);
                        KeyFragment.mTTLockAPI.connect(localKey.getLockMac());
                    }else {//纯门锁
                        ActivityGuanLiKey.bleSession.setOperation(Operation.CLEARICCARD);
                        ActivityGuanLiKey.mTTLockAPI.connect(localKey.getLockMac());
                    }

                    showProgressDialog("正在清空ic卡列表请稍后...",true);
                }
                break;
            case R.id.addICCard:
                selectICCard.setVisibility(View.GONE);
                isShow=!isShow;
                Intent intent = new Intent(this, ActivityAddICCard.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //ic卡列表
        userPresenter.icCardList(uid,localKey.getLockId(),"1","20","0");
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity= (ResultEntity) data;
        commend_anchor_ptr.refreshComplete();
        if (entity!=null){
            if (entity.getEventType()==UserPresenter.BY_ScienerV3_listIcCards_success){
                if (mList.size()>0){
                    mList.clear();
                }
                ICCardListBean bean= (ICCardListBean) entity.getData();
                mList.addAll(bean.getList());
                Log.d("=======list",mList.toString());
                mAdapter.addData(mList);
                if (mList.size()>0){
                    liner_nokey.setVisibility(View.GONE);
                    commend_anchor_ptr.setVisibility(View.VISIBLE);

                }else {
                    liner_nokey.setVisibility(View.VISIBLE);
                    commend_anchor_ptr.setVisibility(View.GONE);
                }
            }else if (entity.getEventType()==UserPresenter.BY_ScienerV3_listIcCards_fail){

            }
        }
    }
}
